package me.younian.transmitNIO;

/**
 * Created by Administrator on 2017/4/1.
 */

import org.apache.log4j.Logger;
import org.apache.mina.core.future.IoFutureListener;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class HandlerUser extends IoHandlerAdapter {
    private static final Logger logger = Logger.getLogger(HandlerUser.class);


    @Override
    public void sessionOpened(IoSession session) {
        // set idle time to 60 seconds
        session.getConfig().setIdleTime(IdleStatus.BOTH_IDLE, 60);
    }

    @Override
    public void messageReceived(IoSession session, Object message) {
        // Check that we can service the request context
        HttpRequestMessage request = (HttpRequestMessage) message;

        if (ClientSession.getClientSession() == null) {
            logger.error("Client Off Line, Return ....");
            HttpResponseMessage response = new HttpResponseMessage();
            response.setHeaders("Content-Type", "text/plain");
            response.setResponseCode(HttpResponseMessage.HTTP_STATUS_SUCCESS);
            response.appendBody("Client Off Line");
            session.write(response).addListener(IoFutureListener.CLOSE);
            return;
        }
        UUID uuid = UUID.randomUUID();
        RequestMap.map.put(uuid.toString(), session);
        logger.info("Transmit: " + request.getContext());
        Map<String, Object> map = new HashMap<>();
        map.put("id", uuid.toString());
        map.put("req", request);

        ClientSession.getClientSession().write(map);
    }

    @Override
    public void sessionIdle(IoSession session, IdleStatus status) {
        logger.info("sessionIdle");
        session.close(false);
    }

    @Override
    public void exceptionCaught(IoSession session, Throwable cause) {
        logger.info("exceptionCaught ");
        cause.printStackTrace();
        session.close(false);
    }
}
